//
//  UserAccount.swift
//  微博
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit


/// 创建模型数据添加用户的属性
class UserAccount: NSObject,NSCoding {
    /**
    *  	用于调用access_token，接口获取授权后的access token。
    */
    var access_token:String?
    /**
    *  access_token的生命周期，单位是秒数。
    */
    var expires_in:NSTimeInterval = 0 {
        didSet{
            //当设置饿了生命周期,就设置死亡的时间
            expires_dead = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //设置一个token死亡的时间
    var expires_dead:NSDate?
    /**
    *  当前授权用户的UID。
    */
    var uid:String?
    /**
    *  友好显示名称
    */
    var name:String?
    /**
    *  用户头像地址（大图），180×180像素
    */
    var avatar_large:String?
    
    //创建构造方法
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    //没有赋值对应key的操作
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    //描述字符串
    override var description: String {
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_dead"]
        //返回描述属性
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //实现归档解档的代理方法
    func saveAccount() {
         let path = (NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("account.plist")
        //归档
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    //解档
    class func loadAccount() ->UserAccount? {
        //获得路径
        let path = (NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first! as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            //对现在的token的时间进行比较,判断是否死亡,如果死亡就返回nil
            if account.expires_dead?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            //解档
            return account
            }
        }
        return nil
    }
    
    
    /**
    归档
    */
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_dead, forKey: "expires_dead")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_dead = aDecoder.decodeObjectForKey("expires_dead") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
        
}
    

